package com.ymttest.business.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.http.client.ClientProtocolException;

import com.ymatou.iapi.selleraccount.parameter.FindMasterByUserIDBean;
import com.ymatou.iapi.selleraccount.service.FindMasterByUserIDCall;
import com.ymatou.iapi.sellercs.parameter.*;
import com.ymatou.iapi.sellercs.service.*;
import com.ymt.core.tool.Logger;
import com.ymttest.database.sqlwapper.JUserWapper;
import com.ymttest.database.sqlwapper.YmtSellerCSIMWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

/************************************************************************************
 * @File name :SellerCSIMCallService.java
 * @Author : zhouyi
 * @Date : 2018年10月10日
 * @Copyright : 洋码头 sellercs.iapi.ymatou.com new java sellercsim.iapi.ymatou.com
 *            old .net
 ************************************************************************************/
public class SellerCSIMCallService {
	// java or net
	public static String ManualTurnTo = "net";
	public static Integer CsimId = 20124241;

	/**
	 * pc登入
	 * 
	 * @param mcsid
	 *            商家主账号uid
	 * @param csid
	 *            子客服uid
	 * @param SocketIoToken
	 *            pc前端token
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void PcLogin(Integer mcsid, Integer csid, String SocketIoToken) throws ClientProtocolException, IOException {
		String name = new JUserWapper().selectUserinfoByUid(csid).get(0).getLoginId();
		PcLoginBean pcloginBean = new PcLoginBean();
		PcLoginCall pcloginCall = new PcLoginCall();
		pcloginBean.setMasterCsId(mcsid);
		pcloginBean.setCsId(csid);
		pcloginBean.setCsName(name);
		pcloginBean.setSocketIoToken(SocketIoToken);
		pcloginCall.setData(false, pcloginBean);
		pcloginCall.callService();
	}

	/**
	 * 商家客服下线-app+pc
	 * 
	 * @param csid
	 *            如果不为null 执行app下线
	 * @param SocketIoToken
	 *            如果不为null 执行pc下线
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void OffLine(Integer csid, String SocketIoToken) throws ClientProtocolException, IOException {
		if (csid != null) {
			AppOffLineBean appofflineBean = new AppOffLineBean();
			AppOffLineCall appofflineCall = new AppOffLineCall();
			appofflineBean.setUserId(csid);
			appofflineCall.setData(false, appofflineBean);
			appofflineCall.callService();
		}
		if (SocketIoToken != null && SocketIoToken.length() > 0) {
			PcOffLineBean pcofflineBean = new PcOffLineBean();
			PcOffLineCall pcofflineCall = new PcOffLineCall();
			pcofflineBean.setOffLineType(1);
			pcofflineBean.setSocketIoToken(SocketIoToken);
			pcofflineCall.setData(false, pcofflineBean);
			pcofflineCall.callService();
		}
	}

	/**
	 * app登入
	 * 
	 * @param csid
	 *            子客服uid
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void AppLogin(Integer csid) throws ClientProtocolException, IOException {
		String name = new JUserWapper().selectUserinfoByUid(csid).get(0).getLoginId();
		AppLoginBean apploginBean = new AppLoginBean();
		AppLoginCall apploginCall = new AppLoginCall();
		apploginBean.setUserId(csid);
		apploginBean.setUserName(name);
		apploginCall.setData(false, apploginBean);
		apploginCall.callService();
	}

	/**
	 * 客服离线
	 * 
	 * @param csid
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void LeaveLine(Integer csid) throws ClientProtocolException, IOException {
		LeaveLineBean leavelineBean = new LeaveLineBean();
		LeaveLineCall leavelineCall = new LeaveLineCall();
		leavelineBean.setCSId(csid);
		leavelineCall.setData(false, leavelineBean);
		leavelineCall.callService();
	}

	/**
	 * 客服上线
	 * 
	 * @param csid
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void OnLine(Integer csid) throws ClientProtocolException, IOException {
		OnLineBean onlineBean = new OnLineBean();
		OnLineCall onlineCall = new OnLineCall();
		onlineBean.setCSId(csid);
		onlineCall.setData(false, onlineBean);
		onlineCall.callService();
	}

	/**
	 * 调用分配会话job
	 * 
	 * @param csid
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws InterruptedException 
	 */
	public static void Assign() throws ClientProtocolException, IOException, InterruptedException {
		Thread.sleep(1000);
		AssignBean assignBean = new AssignBean();
		AssignCall assignCall = new AssignCall();
		assignBean.setAppId("autotest");
		assignCall.setData(false, assignBean);
		assignCall.callService();
	}

	/**
	 * 移动到历史会话
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void MoveClosesessionToHistorySessionTable() throws ClientProtocolException, IOException {
		MoveCloseSessionToHistorySessionTableBean moveclosesessiontohistorysessiontableBean = new MoveCloseSessionToHistorySessionTableBean();
		MoveCloseSessionToHistorySessionTableCall moveclosesessiontohistorysessiontableCall = new MoveCloseSessionToHistorySessionTableCall();
		moveclosesessiontohistorysessiontableBean.setAppId("auto");
		moveclosesessiontohistorysessiontableCall.setData(moveclosesessiontohistorysessiontableBean);
		moveclosesessiontohistorysessiontableCall.callService();
	}

	/**
	 * 初始化SendMessage bean
	 * 
	 * @param userId
	 * @param sellerId
	 * @param msg
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static SendMessageBean initSendmessageBean(Integer userId, Integer sellerId, String msg) throws ClientProtocolException, IOException {
		SendMessageBean sendmessageBean = new SendMessageBean();
		sendmessageBean.setAutoSetRead(true);
		sendmessageBean.setContent("Content");
		sendmessageBean.setCSId(sellerId);
		sendmessageBean.setCSName(JUserCallService.GetUserInfo(sellerId).getLoginId());
		sendmessageBean.setFromUserId(userId);
		sendmessageBean.setIsAutoReply(true);
		sendmessageBean.setMessage(msg);
		sendmessageBean.setNeedAutoReply(true);
		sendmessageBean.setToUserId(sellerId);
		return sendmessageBean;
	}

	/**
	 * 用户给客服发消息
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static SendMessageResp SendMessage(SendMessageBean sendmessageBean) throws ClientProtocolException, IOException {
		SendMessageCall sendmessageCall = new SendMessageCall();
		sendmessageCall.setData(false, sendmessageBean);
		sendmessageCall.callService();
		return sendmessageCall.getResult();
	}

	/**
	 * 客服发消息
	 * 
	 * @param sellerId
	 * @param userid
	 * @param msg
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void SellerSendMessage(Integer sellerId, Integer userid, String msg) throws ClientProtocolException, IOException {
		SellerSendMessageBean sellersendmessageBean = new SellerSendMessageBean();
		SellerSendMessageCall sellersendmessageCall = new SellerSendMessageCall();
		sellersendmessageBean.setCsId(sellerId);
		sellersendmessageBean.setMasterCSId(sellerId);
		sellersendmessageBean.setMessage(msg);
		sellersendmessageBean.setUserId(userid);
		sellersendmessageCall.setData(sellersendmessageBean);
		sellersendmessageCall.callService();
	}

	/**
	 * 发送一个带附件的消息demo
	 * 
	 * @param userId
	 * @param sellerId
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static SendMessageWithAttachBean SendMessageWithAttach(Integer userId, Integer sellerId) throws ClientProtocolException, IOException {
		SendMessageWithAttachBean sendmessagewithattachBean = new SendMessageWithAttachBean();
		SendMessageWithAttachCall sendmessagewithattachCall = new SendMessageWithAttachCall();
		sendmessagewithattachBean.setCsId(sellerId);
		sendmessagewithattachBean.setMasterCSId(sellerId);
		sendmessagewithattachBean.setMessage("MessageAttach:" + YMTDateUtil.getBeforeOrNextDay(0));
		sendmessagewithattachBean.setUserId(userId);
		List<MessageAttach> MessageAttachList = new ArrayList<MessageAttach>();
		MessageAttach ma = new MessageAttach();
		ma.setContent("{" + " \"MinPrice\" : 6," + " \"TariffType\" : 0," + " \"ProductDesc\" : \"新发布测试商品_zjf\"," + " \"ProductId\" : \"1b2c7efb-77e7-46c3-ab51-05b51c9ae837\","
				+ " \"ProductPics\" : [" + "  \"http:\\/\\/pic1.ymatou.com\\/G01\\/\\/M00\\/3A\\/B5\\/rBBlD1n4KfWAdwsUAAd-Uj1GHqM097.png\"" + " ]," + " \"DeliveryType\" : 3,"
				+ " \"IsPreSale\" : false," + " \"MaxPrice\" : 6," + " \"FreeShipping\" : true," + " \"Price\" : 12," + " \"IsPSPProduct\" : false," + " \"IsNew\" : false" + "}");
		ma.setType(5);
		MessageAttachList.add(ma);
		sendmessagewithattachBean.setMessageAttachList(MessageAttachList);
		sendmessagewithattachCall.setData(false, sendmessagewithattachBean);
		sendmessagewithattachCall.callService();
		return sendmessagewithattachBean;
	}

	/**
	 * 商家客服设置重要消息
	 * 
	 * @param otheruserid
	 * @param userid
	 *            设置会话uid 商家客服设置重要消息时这里传sellerid
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void SetMessageSessionImportant(Integer otheruserid, Integer userid) throws ClientProtocolException, IOException {
		SetMessageSessionImportantBean setmessagesessionimportantBean = new SetMessageSessionImportantBean();
		SetMessageSessionImportantCall setmessagesessionimportantCall = new SetMessageSessionImportantCall();
		setmessagesessionimportantBean.setToUserId(otheruserid);
		setmessagesessionimportantBean.setUserId(userid);
		setmessagesessionimportantCall.setData(false, setmessagesessionimportantBean);
		setmessagesessionimportantCall.callService();
	}

	/**
	 * 商家客服取消设置重要消息
	 * 
	 * @param sellerid
	 * @param userid
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void CancelSetMessageSessionImportant(Integer sellerid, Integer userid) throws ClientProtocolException, IOException {
		CancelSetMessageSessionImportantBean cancelsetmessagesessionimportantBean = new CancelSetMessageSessionImportantBean();
		CancelSetMessageSessionImportantCall cancelsetmessagesessionimportantCall = new CancelSetMessageSessionImportantCall();
		cancelsetmessagesessionimportantBean.setToUserId(sellerid);
		cancelsetmessagesessionimportantBean.setUserId(userid);
		cancelsetmessagesessionimportantCall.setData(false, cancelsetmessagesessionimportantBean);
		cancelsetmessagesessionimportantCall.callService();
	}

	/**
	 * 获取消息列表
	 * 
	 * @param sellerid
	 * @param userid
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static ArrayList<MessageResp> GetMessageList(Integer sellerid, Integer userid, boolean clearUnRead) throws ClientProtocolException, IOException {
		Integer mcsid = FindMasterByUserIDCall(sellerid);
		GetMessageListBean getmessagelistBean = new GetMessageListBean();
		GetMessageListCall getmessagelistCall = new GetMessageListCall();
		getmessagelistBean.setClearUnRead(clearUnRead);
		getmessagelistBean.setCSId(sellerid);
		getmessagelistBean.setIsNew(false);
		getmessagelistBean.setLongTimeline(0l);
		getmessagelistBean.setMasterCSId(mcsid);
		getmessagelistBean.setMessageCount(20);
		getmessagelistBean.setToUserId(userid);
		getmessagelistCall.setData(false, getmessagelistBean);
		getmessagelistCall.callService();
		return getmessagelistCall.getResult();
	}

	/**
	 * 获取全部session info
	 * 
	 * @param sellerId
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static ArrayList<GetCurrentSessionListResp> GetAllSessionListInfo(Integer sellerId) throws ClientProtocolException, IOException, InterruptedException {
		Integer mcsid = FindMasterByUserIDCall(sellerId);
		GetCurrentSessionListBean getcurrentsessionlistBean = new GetCurrentSessionListBean();
		GetCurrentSessionListCall getcurrentsessionlistCall = new GetCurrentSessionListCall();
		getcurrentsessionlistBean.setCount(50);
		getcurrentsessionlistBean.setCSId(sellerId);
		getcurrentsessionlistBean.setMasterCSId(mcsid);
		getcurrentsessionlistBean.setLongPostTime(0l);
		getcurrentsessionlistBean.setMessageImportantType("All");
		getcurrentsessionlistCall.setData(false, getcurrentsessionlistBean);
		getcurrentsessionlistCall.callService();
		ArrayList<GetCurrentSessionListResp> results = getcurrentsessionlistCall.getResult();
		int diffsize = results.size();
		while (diffsize > 0) {
			getcurrentsessionlistBean.setLongPostTime(results.get(results.size() - 1).getLastMessageTime().getTime());
			getcurrentsessionlistCall.callService();
			results.addAll(getcurrentsessionlistCall.getResult());
			diffsize = getcurrentsessionlistCall.getResult().size();
		}
		return results;
	}

	/**
	 * 设置商家没有未读消息
	 * 
	 * @param sellerid
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws InterruptedException
	 */
	public static void setNoUnRead(Integer sellerid) throws ClientProtocolException, IOException, InterruptedException {
		GetAllSessionListInfo(sellerid).forEach(sinfo -> {
			try {
				GetMessageList(sellerid, sinfo.getToUserId(), true);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
		;
	}

	/**
	 * 获取总未读数
	 * 
	 * @param sellerid
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws InterruptedException 
	 */
	public static Integer getUnReadNum(Integer sellerid) throws ClientProtocolException, IOException, InterruptedException {
		Thread.sleep(1000);
		return CounterCallService.getSingleValue("IM", sellerid.toString(), "SellerMessage");
	}

	public static Integer FindMasterByUserIDCall(Integer sellerid) throws ClientProtocolException, IOException {
		FindMasterByUserIDCall FindMasterByUserIDCall = new FindMasterByUserIDCall();
		FindMasterByUserIDBean FindMasterByUserIDBean = new FindMasterByUserIDBean();
		FindMasterByUserIDBean.setUserId(sellerid);
		FindMasterByUserIDCall.setData(false, FindMasterByUserIDBean);
		FindMasterByUserIDCall.callService();
		return FindMasterByUserIDCall.getJsonObject().get("Data").getAsJsonObject().get("SellerID").getAsInt();
	}

	/**
	 * 获取话术id,如果没有则新建一个并获取
	 * 
	 * @param sellerid
	 * @param icTitle
	 *            话术类别名
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static String getCategoryId(Integer sellerid, String icTitle) throws ClientProtocolException, IOException, InterruptedException {
		YmtSellerCSIMWapper YmtSellerCSIMWapper = new YmtSellerCSIMWapper();
		List<Map> m = YmtSellerCSIMWapper.selectIndividualdiscourseByCsid(sellerid).stream().filter(map -> {
			return map.get("icTitle").equals(icTitle);
		}).collect(Collectors.toList());
		if (m != null && m.size() > 0) {
			return m.get(0).get("CategoryId").toString();
		} else {
			AddCategoryBean addcategoryBean = new AddCategoryBean();
			AddCategoryCall addcategoryCall = new AddCategoryCall();
			addcategoryBean.setCSId(sellerid);
			addcategoryBean.setTitle(icTitle);
			addcategoryBean.setSort(1);
			addcategoryCall.setData(addcategoryBean);
			addcategoryCall.callService();
			m = YmtSellerCSIMWapper.selectIndividualdiscourseByCsid(sellerid).stream().filter(map -> {
				return map.get("icTitle").equals(icTitle);
			}).collect(Collectors.toList());
			return m.get(0).get("CategoryId").toString();
		}
	}

	/**
	 * 增加话题
	 * 
	 * @param sellerid
	 * @param icTitle
	 *            分类
	 * @param discourse
	 *            话术
	 * @return 话术id
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static String AddDiscourse(Integer sellerid, String icTitle, String discourse) throws ClientProtocolException, IOException, InterruptedException {
		AddDiscourseBean adddiscourseBean = new AddDiscourseBean();
		AddDiscourseCall adddiscourseCall = new AddDiscourseCall();
		String CategoryId = getCategoryId(sellerid, icTitle);
		adddiscourseBean.setCategoryId(CategoryId);
		adddiscourseBean.setCSId(sellerid);
		adddiscourseBean.setSort(2);
		adddiscourseBean.setTitle(discourse);
		adddiscourseCall.setData(adddiscourseBean);
		adddiscourseCall.callService();
		YmtSellerCSIMWapper YmtSellerCSIMWapper = new YmtSellerCSIMWapper();
		List<Map> m = YmtSellerCSIMWapper.selectIndividualdiscourseByCsid(sellerid).stream().filter(map -> {
			if (map.get("icTitle").equals(icTitle) && map.get("cTitle").equals(discourse)) {
				return true;
			} else {
				return false;
			}
		}).collect(Collectors.toList());
		if (m.size() <= 0) {
			return null;
		} else {
			return m.get(0).get("id").toString();
		}
	}

	/**
	 * 删除所有话术
	 * 
	 * @param sellerid
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void DelAllDiscourse(Integer sellerid) throws ClientProtocolException, IOException, InterruptedException {
		YmtSellerCSIMWapper YmtSellerCSIMWapper = new YmtSellerCSIMWapper();
		YmtSellerCSIMWapper.selectIndividualdiscourseByCsid(sellerid).stream().forEach(map -> {
			DeleteCategoryBean deletecategoryBean = new DeleteCategoryBean();
			DeleteCategoryCall deletecategoryCall = new DeleteCategoryCall();
			deletecategoryBean.setCategoryId(map.get("CategoryId").toString());
			deletecategoryBean.setCSId(sellerid);
			deletecategoryCall.setData(deletecategoryBean);
			try {
				deletecategoryCall.callService();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		});

	}

	public static void main(String args[]) throws NumberFormatException, ClientProtocolException, IOException, InterruptedException {
		int sellerid = Integer.parseInt(EnvSetup.getData("autotest_seller1"));
		// SellerCSIMCallService.setNoUnRead(sellerid);
		// Logger.debug("count:"+SellerCSIMCallService.FindMasterByUserIDCall(sellerid));
	}
}
